<?php
require_once __DIR__ . '/../functions.php';

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 只允许 DELETE 方法
if ($_SERVER['REQUEST_METHOD'] !== 'DELETE') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

$userInfo = getUserInfo();
$orderId = intval($_GET['id'] ?? 0);

if ($orderId <= 0) {
    echo json_encode(['success' => false, 'message' => '订单ID无效']);
    exit;
}

$db = getDB();

// 获取订单信息，确保是当前用户的且未结算的订单
$stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ? AND status = 'pending'");
$stmt->execute([$orderId, $userInfo['id']]);
$order = $stmt->fetch();

if (!$order) {
    echo json_encode(['success' => false, 'message' => '订单不存在或无法删除']);
    exit;
}

// 检查订单是否已经被包含在结算记录中
$stmt = $db->prepare("SELECT id FROM settlements WHERE FIND_IN_SET(?, REPLACE(REPLACE(order_ids, '[', ''), ']', '')) AND status = 'completed'");
$stmt->execute([$orderId]);
if ($stmt->fetch()) {
    echo json_encode(['success' => false, 'message' => '该订单已结算，无法删除']);
    exit;
}

// 开始事务
$db->beginTransaction();

try {
    // 删除订单截图文件
    if ($order['order_screenshot']) {
        deleteFile($order['order_screenshot'], 'order_screenshot');
    }
    
    // 删除结算截图文件（如果有）
    if ($order['settlement_screenshot']) {
        deleteFile($order['settlement_screenshot'], 'settlement_screenshot');
    }
    
    // 删除订单操作记录
    $stmt = $db->prepare("DELETE FROM order_operations WHERE order_id = ?");
    $stmt->execute([$orderId]);
    
    // 从结算明细中删除相关记录
    $stmt = $db->prepare("DELETE FROM settlement_details WHERE order_id = ?");
    $stmt->execute([$orderId]);
    
    // 删除订单
    $stmt = $db->prepare("DELETE FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    
    // 提交事务
    $db->commit();
    
    echo json_encode(['success' => true, 'message' => '订单删除成功']);
    
} catch (Exception $e) {
    // 回滚事务
    $db->rollBack();
    error_log("删除订单失败: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => '删除失败，请重试']);
}
?>